//
//  ARTWatchMonitoringController.m
//  ChartsDemo
//
//  Created by 刘权 on 2021/10/11.
//

#import "ARTWatchMonitoringController.h"
// controllers
#import "ARTWatchHistorySleepController.h"
// views
#import "CircleView.h"
// models
#import "ARTWathDataAnalysis.h"
#import "ARTWatchHisModel.h"

@interface ARTWatchMonitoringController ()<AVAudioPlayerDelegate>{
    BOOL isGoDetail;
    BOOL isSaveDailyData;
    NSInteger lowSpo_count;
    NSInteger lowPr_count;
    NSInteger highPr_count;
}

@property (weak, nonatomic) IBOutlet UIView *timeViewbg;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

@property (weak, nonatomic) IBOutlet UIView *spoViewbg;
@property (weak, nonatomic) IBOutlet UILabel *spoLabel;

@property (weak, nonatomic) IBOutlet UILabel *piLabel;


@property (weak, nonatomic) IBOutlet UIView *prViewbg;
@property (weak, nonatomic) IBOutlet UILabel *prLabel;
@property (weak, nonatomic) IBOutlet UIImageView *heartImageView;
@property (weak, nonatomic) IBOutlet UIImageView *loveImageView;

@property (weak, nonatomic) IBOutlet UILabel *alertLabel;
@property (weak, nonatomic) IBOutlet UIButton *stopButton;

@property (strong, nonatomic)  CircleView *spoCircleView;
@property (strong, nonatomic)  CircleView *prCircleView;

// 连接状态
@property (assign, nonatomic)  BOOL  isConnected;

@property (strong, nonatomic)  ARTWathDataAnalysis *dataAnalysis;
@property (strong, nonatomic)  ARTWathDataModel *realDataModel;
@property (strong, nonatomic)  ARTWatchHisModel *hisModel;

// 计时器
@property (strong, nonatomic) NSTimer *dataTimer;
@property (assign, nonatomic)  NSInteger  timerCount;

// 闪烁动画计时器
@property (strong, nonatomic) NSTimer *animationTimer;
@property (assign, nonatomic)  NSInteger  animationCount;

@property (strong, nonatomic)  UIButton *rightButton;

@property (strong, nonatomic)  AVAudioPlayer *audioPlayer;

@property (strong, nonatomic) NSTimer *testTimer;

@end

@implementation ARTWatchMonitoringController

//- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    [super touchesBegan:touches withEvent:event];
//    self.testTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(testAction) userInfo:nil repeats:YES];
//    [[NSRunLoop currentRunLoop] addTimer:self.testTimer forMode:NSRunLoopCommonModes];
//}
//
//- (void)testAction{
//    ARTWathDataModel *model = [[ARTWathDataModel alloc]init];
//    model.spo2 = 90;
//    model.pr = 35;
//    model.lowSpo = 94;
//    model.lowPr = 40;
//    model.highPr = 120;
//    model.pi = 10;
//    self.realDataModel = model;
//}

#pragma mark--THE LIFE CYCLE
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.timerCount = 0;
    self.animationCount = 1;
    
    J_Add_Notify(self, @selector(refreshLanguage), ART_Notify_LanguageChanged, nil);
    [self refreshLanguage];
    
    self.hisModel = [[ARTWatchHisModel alloc]init];
    self.hisModel.date = [[NSDate date] j_stringWithFormat:@"yyyy/MM/dd HH:mm:ss"];
    self.hisModel.dataList = [NSMutableArray array];
    // 设置蓝牙代理
    [self babyDelegate];
    // 初始化定时器
    [self initTimer];
    
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:nil];
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
}

- (void)viewDidDisappear:(BOOL)animated{;
    [super viewDidDisappear:animated];
    [self destoryTimer];
    [self stopAudioPlay];
}

- (void)initSubviews{
    [super initSubviews];
    J_ViewRadius(_timeViewbg, 32/2);
    J_ViewBorder(_timeViewbg, J_ColorFromHEX(0xCCCCCC), 0.5);
    
    J_ViewRadius(_stopButton, 5);
    [_stopButton setBackgroundImage:[UIImage qmui_imageWithColor:J_ColorFromHEX(0x0095B6)] forState:UIControlStateNormal];
    [_stopButton setBackgroundImage:[UIImage qmui_imageWithColor:J_ColorFromHEX(0xCCCCCC)] forState:UIControlStateDisabled];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self createCircle];
    });
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
}

- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
//    [self createCircle];
}

- (void)createCircle{
    CGFloat circle_W = 140;
    if (isIPhoneX) {
        circle_W = kScale_W(150);
    }
    circle_W = _spoViewbg.v_h;
    if (!_spoCircleView) {
        _spoCircleView = [[CircleView alloc] initWithFrame:_spoViewbg.bounds];
        _spoCircleView.titleLab.text = @"0";
        _spoCircleView.tipLab.text = @"SpO2%";
        _spoCircleView.leftLab.text = @"70";
        _spoCircleView.rightLab.text = @"100";
        [_spoViewbg addSubview:_spoCircleView];
    }
    if (!_prCircleView) {
        _prCircleView = [[CircleView alloc] initWithFrame:_prViewbg.bounds];
        _prCircleView.titleLab.text = @"0";
        _prCircleView.tipLab.text = @"times_min";//[NSString stringWithFormat:@"%@/min",FYLocalizedString(@"oxygen_pr", @"")];
        _prCircleView.leftLab.text = @"30";
        _prCircleView.rightLab.text = @"250";
        [_prViewbg addSubview:_prCircleView];
    }
}

- (void)dealloc{
    J_Remove_Notify(self);
}

/// 返回按钮事件
- (void)hookBackBarButtonAction:(UIButton *)sender{
    [self goBack];
}

#pragma mark--PRIVATE METHOD
- (void)refreshLanguage{
    if (_monitorType == ARTWatchMonitorTypeDaily) {
        self.title = FYLocalizedString(@"sleep_watch_daily_test", @"");
        _alertLabel.text = @"";
    }else{
        self.title = FYLocalizedString(@"sleep_watch_sleep_test", @"");
        _alertLabel.text = FYLocalizedString(@"sleep_watch_no_time", @"");
    }
    
    _spoLabel.textColor = _prLabel.textColor = J_ColorFromHEX(0x222222);
    _spoLabel.font = _prLabel.font = j_SemiboldFont(18);
    _spoLabel.text = FYLocalizedString(@"oxygen_spo2", @"");//@"Blood oxygen";
    _prLabel.text = FYLocalizedString(@"oxygen_pr", @"");//@"Heart rate";
    
    self.realDataModel = _realDataModel;
    
    [_stopButton setTitle:FYLocalizedString(@"sleep_watch_sleep_endmonitor", @"") forState:UIControlStateNormal];
}

// 设置蓝牙代理
- (void)babyDelegate{
    if (!_baby || !_currentPeripheral || !_notifyCharacteristic || !_writeCharacteristic) {
        return;
    }
    J_WeakSelf(self)
    // 监听蓝牙数据
    [_baby notify:_currentPeripheral characteristic:_notifyCharacteristic block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        J_StrongSelf(self)
        self.isConnected = YES;
        [self.dataAnalysis analysisData:characteristics.value];
//        if (self.dataAnalysis.bufferData) {
//            [self.dataAnalysis.bufferData appendData:characteristics.value];
//        }
    }];
        
    // 断开连接
    [self.baby setBlockOnDisconnect:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        J_StrongSelf(self)
        self.isConnected = NO;
        if (!error) {
            NSLog(@"====手动断开连接设备2name：%@",peripheral.name);
        }else{
            NSLog(@"====自动断开连接设备2name：%@,error:%@",peripheral.name,error);
        }
        if (self->isGoDetail == NO) {
            [QMUITips hideAllTips];
            if (self.disConnectBlock) {
                self.disConnectBlock();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
}

// 初始化定时器
- (void)initTimer{
    NSLog(@"--初始化定时器");
    if (_monitorType == ARTWatchMonitorTypeDaily) {
        self.dataTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.dataTimer forMode:NSRunLoopCommonModes];
    }
    
    self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(animationAction:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.animationTimer forMode:NSRunLoopCommonModes];
}

// 销毁定时器
- (void)destoryTimer{
    NSLog(@"--销毁定时器");
    if (self.dataTimer) {
        [self.dataTimer invalidate];
        self.dataTimer = nil;
    }
    if (self.animationTimer) {
        [self.animationTimer invalidate];
        self.animationTimer = nil;
    }
}

// 添加心跳动画
- (void)addHeartAnimation{
    if (_realDataModel.isValid) {
        if (![_loveImageView.layer.animationKeys containsObject:@"scale"]) {
            CABasicAnimation *pulseAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
             pulseAnimation.duration = 0.25;
             pulseAnimation.toValue = [NSNumber numberWithFloat:1.3];
             pulseAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
             pulseAnimation.autoreverses = YES;
             pulseAnimation.repeatCount = FLT_MAX;
             // 添加动画到layer
             [_loveImageView.layer addAnimation:pulseAnimation forKey:@"scale"];
            
            [self.animationTimer jk_resumeTimer];
        }
    }else{
        [_loveImageView.layer removeAnimationForKey:@"scale"];
        [self.animationTimer jk_pauseTimer];
        self.animationCount = 1;
    }
}

#pragma mark--TARGET ACTION
- (void)timerAction:(NSTimer *)sender {
    self.timerCount++;
}

- (void)animationAction:(NSTimer *)sender {
    if (self.animationCount == 6) {
        self.animationCount = 1;
    }else{
        self.animationCount++;
    }
}

- (IBAction)stopAction:(id)sender {
    [self goBack];
}

- (void)goBack{
    if (_monitorType == ARTWatchMonitorTypeDaily) {
        // 日常
        if (_timerCount < 10) {
            [self lq_showAlertControllerWithMessage:FYLocalizedString(@"sleep_watch_end_time_n", @"") cancleHandle:^{

            } okHandle:^{
//                [self sendStop];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [self lq_showAlertControllerWithMessage:FYLocalizedString(@"sleep_watch_end", @"") cancleHandle:^{
            } okHandle:^{
//                [self sendStop];
                NSLog(@"手动保存");
                if (self->isSaveDailyData == NO) {
                    [self saveDailyData];
                }
            }];
        }
    }else{
        // 睡眠
        if (_realDataModel.timeInterval < 30*60) {
            [self lq_showAlertControllerWithMessage:FYLocalizedString(@"sleep_watch_end_time", @"") cancleHandle:^{

            } okHandle:^{
                [self sendStop];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [self lq_showAlertControllerWithMessage:FYLocalizedString(@"Are you sure you want to stop monitoring?", @"") cancleHandle:^{

            } okHandle:^{
                [self sendStop];
                [QMUITips showLoading:FYLocalizedString(@"sleep_watch_Report_generation", @"") inView:self.view hideAfterDelay:60*10];
//                self.dataAnalysis.bufferData = [NSMutableData data];
            }];
        }
    }
}

- (void)sendStop{
    [self.currentPeripheral writeValue:[ARTWathDataAnalysis syncStop] forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
}

- (void)saveDailyData{
    isSaveDailyData = YES;
//    ARTWathDataModel *first = self.hisModel.dataList.firstObject;
    NSInteger spoMin = 500;//first.spo2;
    NSInteger spoMax = 0;//first.spo2;
    NSInteger prMin = 500;//first.pr;
    NSInteger prMax = 0;//first.pr;
    long spo2Sum = 0,prSum = 0;
    NSInteger count = 0;
    for (ARTWathDataModel *model in self.hisModel.dataList) {
        if (model.spo2 != 0 && model.pi != 0) {
            spoMin = MIN(spoMin, model.spo2);
            spoMax = MAX(spoMax, model.spo2);
            prMin = MIN(prMin, model.pr);
            prMax = MAX(prMax, model.pr);
            spo2Sum = spo2Sum + model.spo2;
            prSum = prSum + model.pr;
            count++;
        }
    }
    self.hisModel.spo2Min = spoMin;
    self.hisModel.spo2Max = spoMax;
    self.hisModel.spo2Avg = spo2Sum/count;
    self.hisModel.prMin = prMin;
    self.hisModel.prMax = prMax;
    self.hisModel.prAvg = prSum/count;
    
    Byte *IDBytes = (Byte *)[ARTSingleShare.currentSettingData bytes];
    self.hisModel.ID = IDBytes[5]&0xff;
    
    self.hisModel.lookState = 1;
    self.hisModel.type = _monitorType;
    self.hisModel.longTime = _timerCount;
    
    [self.hisModel syncStoreData];
    
//    NSArray *historys = [[NSUserDefaults standardUserDefaults] objectForKey:App_History_DailyWatch];
//    NSDictionary *dict = [self.hisModel mj_JSONObject];
//    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:historys];
//    [tempArr insertObject:dict atIndex:0];
//    [NSUserDefaults jk_setObject:tempArr forKey:App_History_DailyWatch];
    
    NSArray *historys = [[NSUserDefaults standardUserDefaults] objectForKey:App_History_DailyWatch];
    NSString *dict = [self.hisModel mj_JSONString];
    dict = [RSAEncryptor encryptSubsectionString:dict publicKey:ART_Pubkey];
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:historys];
    [tempArr insertObject:dict atIndex:0];
    [NSUserDefaults jk_setObject:tempArr forKey:App_History_DailyWatch];
    
    [QMUITips showWithText:FYLocalizedString(@"oxygen_saved_successfully", @"")];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popViewControllerAnimated:YES];
    });
}

- (void)saveSleepData{
    if (!self.hisModel.time_start || !self.hisModel.time_end) {
        return;
    }
    Byte *IDBytes = (Byte *)[ARTSingleShare.currentSettingData bytes];
    self.hisModel.ID = IDBytes[5]&0xff;
    [self.hisModel syncStoreData];
    
//    NSArray *historys = [[NSUserDefaults standardUserDefaults] objectForKey:App_History_SleepWatch];
//    NSDictionary *dict = [self.hisModel mj_JSONObject];
//    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:historys];
//    [tempArr insertObject:dict atIndex:0];
//    [NSUserDefaults jk_setObject:tempArr forKey:App_History_SleepWatch];
    
    NSArray *historys = [[NSUserDefaults standardUserDefaults] objectForKey:App_History_SleepWatch];
    NSString *dict = [self.hisModel mj_JSONString];
    dict = [RSAEncryptor encryptSubsectionString:dict publicKey:ART_Pubkey];
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:historys];
    [tempArr insertObject:dict atIndex:0];
    [NSUserDefaults jk_setObject:tempArr forKey:App_History_SleepWatch];
}

#pragma mark--AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self stopAudioPlay];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark--SETTER
- (void)setIsConnected:(BOOL)isConnected{
    _isConnected = isConnected;
    if (!isConnected) {
        self.realDataModel = nil;
    }
}

- (void)setTimerCount:(NSInteger)timerCount{
    _timerCount = timerCount;
    _timeLabel.text = [NSString stringWithFormat:@"%@ %@",FYLocalizedString(@"oxygen_time_Long", @""),[Tool getMMSSFromSS:timerCount]];
}

- (void)setRealDataModel:(ARTWathDataModel *)realDataModel{
    _realDataModel = realDataModel;
    NSString *spo2 = @"--";
    NSString *pr = @"--";
    NSString *pi = @"--";
    if (realDataModel.isValid) {
        spo2 = [NSString stringWithFormat:@"%@",@(realDataModel.spo2)];
        pr = [NSString stringWithFormat:@"%@",@(realDataModel.pr)];
        pi = [NSString stringWithFormat:@"%.1f",realDataModel.pi];
    }
    _spoCircleView.titleLab.text = spo2;
    _prCircleView.titleLab.text = pr;
    _piLabel.attributedText = [self piAttributeWithValue:pi];
//    if (_monitorType == ARTWatchMonitorTypeDaily) {
//        [_spoCircleView setPercent:spo2.floatValue*1.8 animated:YES];
//        [_prCircleView setPercent:pr.floatValue*1.05 animated:YES];
//    }else{
        [_spoCircleView setSleepPercent:spo2.floatValue*1.8 watchModel:realDataModel animated:YES];
        [_prCircleView setSleepPercent:pr.floatValue*1.05 watchModel:realDataModel animated:YES];
//    }
    
    [self addHeartAnimation];
    
    if (_monitorType == ARTWatchMonitorTypeSleep) {
        NSString *timeString = [NSString stringWithFormat:@"%@ %@",FYLocalizedString(@"oxygen_time_Long", @""),[Tool getMMSSFromSS:realDataModel.timeInterval]];
        if ([timeString isEqualToString:_timeLabel.text]) {
            NSLog(@"睡眠监测时长相等:%@",@(realDataModel.timeInterval));
        }
        _timeLabel.text = timeString;
    }
    
    // 播放异常音频
    NSInteger maxCount = 40;
    if (realDataModel.spo2 < realDataModel.lowSpo) {
        lowSpo_count++;
    }else{
        lowSpo_count = 0;
    }
    if (realDataModel.pr < realDataModel.lowPr) {
        lowPr_count++;
        highPr_count = 0;
    }else if (realDataModel.pr > realDataModel.highPr){
        highPr_count++;
        lowPr_count = 0;
    }else{
        lowPr_count = 0;
        highPr_count = 0;
    }
    NSString *audioName = @"";
    if (lowSpo_count >= maxCount) {
        if (highPr_count >= maxCount || lowPr_count >= maxCount) {
            // 血氧脉率都异常
            audioName = @"bloodhearterro";
            NSLog(@"异常报警-血氧脉率都异常=%@",realDataModel.description);
            highPr_count = lowPr_count = 0;
        }else{
            // 血氧异常
            audioName = @"bloodoxygenerror";
            NSLog(@"异常报警-血氧异常=%@",realDataModel.description);
        }
        lowSpo_count = 0;
    }else{
        if (highPr_count >= maxCount || lowPr_count >= maxCount) {
            // 脉率异常
            audioName = @"headrerror";
            NSLog(@"异常报警-脉率异常=%@",realDataModel.description);
            highPr_count = lowPr_count = 0;
        }
    }
    BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_WatchVioceStatus];
    if (!canPlay) {
        if (audioName.length > 0) {
            NSError *error = nil;
            NSString *audioPath = [[NSBundle mainBundle] pathForResource:audioName ofType:@".mp3"];
            if (audioPath) {
                if (_audioPlayer) {
                    if (_audioPlayer.playing) {
                        [_audioPlayer stop];
                    }
                    _audioPlayer = nil;
                }
                NSURL *url = [NSURL fileURLWithPath:audioPath];
                _audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:&error];
                if (!error) {
                    _audioPlayer.delegate = self;
                    _audioPlayer.volume = 1.0;
                    [_audioPlayer prepareToPlay];
                    [_audioPlayer play];
                    [self performSelector:@selector(autoRealsePlayer) withObject:nil afterDelay:10];
//                    [self performSelector:@selector(autoRealsePlayer) afterDelay:10];
                }else{
                    NSLog(@"audio play error=%@",error);
                }
            }
        }
    }
}

- (void)autoRealsePlayer{
    _audioPlayer = nil;
}

- (void)setAnimationCount:(NSInteger)animationCount{
    _animationCount = animationCount;
    _heartImageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"heart%ld",animationCount]];
}

- (NSAttributedString *)piAttributeWithValue:(NSString *)value{
    NSMutableAttributedString *unitAttribute = [[NSMutableAttributedString alloc]initWithString:@"PI：" attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x222222),NSFontAttributeName:j_SemiboldFont(18)}];
    NSAttributedString *valueAttribute = [[NSAttributedString alloc]initWithString:value attributes:@{NSForegroundColorAttributeName:J_ColorFromHEX(0x0095B6),NSFontAttributeName:j_SemiboldFont(18)}];
    [unitAttribute appendAttributedString:valueAttribute];
    return unitAttribute;
}

#pragma mark--GETTER
- (ARTWathDataAnalysis *)dataAnalysis{
    if (!_dataAnalysis) {
        ARTWathDataAnalysis *analysis = [[ARTWathDataAnalysis alloc]init];
        analysis.call_0x10_back = ^(ARTWathDataModel * _Nullable dataModel) {
            self.realDataModel = dataModel;
            [self.hisModel.dataList addObject:dataModel];
        };
        analysis.call_0x13_back = ^(BOOL stop) {
            if (stop) {
                if (self.monitorType == ARTWatchMonitorTypeDaily) {
                    if (self.timerCount < 10) {
                        [self.navigationController popViewControllerAnimated:YES];
                    }else{
                        NSLog(@"自动保存");
                        if (self->isSaveDailyData == NO) {
                            [self saveDailyData];
                        }
                    }
                }
            }
        };
//        J_WeakSelf(analysis);
        analysis.call_0x14_back = ^(NSData * _Nullable datas) {
            [self.currentPeripheral writeValue:datas forCharacteristic:self.writeCharacteristic type:CBCharacteristicWriteWithResponse];
            [QMUITips showLoading:FYLocalizedString(@"sleep_watch_Report_generation", @"") inView:self.view hideAfterDelay:60*10];
//            J_StrongSelf(analysis);
//            analysis.bufferData = [NSMutableData data];
        };
        analysis.call_0x15_back = ^(ARTWatchHisModel * _Nullable hisModel) {
            NSLog(@"同步完成跳转睡眠报告");
            [QMUITips hideAllTips];
            hisModel.type = self.monitorType;
            if (hisModel.type == ARTWatchMonitorTypeSleep) {
                self.hisModel = hisModel;
                [self saveSleepData];
                self->isGoDetail = YES;
                ARTWatchHistorySleepController *controller = [[ARTWatchHistorySleepController alloc]init];
                controller.receiveModel = hisModel;
                controller.popClass = @"ARTMainTabController";
                [self.navigationController pushViewController:controller animated:YES];
            }
        };
        _dataAnalysis = analysis;
    }
    return _dataAnalysis;
}

- (UIButton *)rightButton{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = J_FrameWithSize(40, 40);
        [self configureRightState];
        [_rightButton addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

- (void)configureRightState{
    BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_WatchVioceStatus];
    if (!canPlay) {
        [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_on") forState:UIControlStateNormal];
    }else{
        [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_off") forState:UIControlStateNormal];
    }
}

- (void)rightAction{
    BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_WatchVioceStatus];
    canPlay = !canPlay;
    [NSUserDefaults jk_setObject:@(canPlay) forKey:ART_Storage_WatchVioceStatus];
    [self configureRightState];
    if (!canPlay) {
        // 没有播完，继续播放
        if (_audioPlayer && !_audioPlayer.isPlaying) {
            [_audioPlayer play];
        }
    }else{
        // 如果当前正在播，就暂停
        if (_audioPlayer && _audioPlayer.isPlaying) {
            [_audioPlayer pause];
        }
    }
}

- (void)stopAudioPlay{
    if (_audioPlayer && _audioPlayer.isPlaying) {
        [_audioPlayer stop];
        _audioPlayer = nil;
    }
}

#pragma mark--测试
- (void)shareLogAction{
    NSString *documentDirectory = J_Path_Document;
    NSString *fileName = [NSString stringWithFormat:@"test.txt"];
    NSString *logFilePath = [documentDirectory stringByAppendingPathComponent:fileName];
    NSData *shareData = [NSData dataWithContentsOfFile:logFilePath];
    if (shareData.length == 0) {
        [QMUITips showWithText:@"暂无日志分享"];
        return;
    }
    NSArray *activityItems = @[shareData,[NSURL URLWithString:logFilePath]];
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
    [self presentViewController:activityVC animated:YES completion:nil];
    // 分享之后的回调
    J_WeakSelf(activityVC)
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        J_StrongSelf(activityVC)
        if (completed) {
            // 分享成功
            [activityVC dismissViewControllerAnimated:YES completion:nil];
            if (activityError) {
                [QMUITips showWithText:FYLocalizedString(@"share_fail", @"")];
            }else{
                [QMUITips showWithText:FYLocalizedString(@"share_success", @"")];
            }
        } else  {
            NSLog(@"cancled");
            //分享 取消
            [activityVC dismissViewControllerAnimated:YES completion:nil];
            [QMUITips showWithText:FYLocalizedString(@"share_cancel", @"")];
        }
    };
}

@end
